package com.pishou.shop;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.pishou.URLConfig;
import com.pishou.Data;
import com.pishou.code.bean.Cart;
import com.pishou.code.util.ZXingUtils;
import com.pishou.player.R;
import com.pishou.player.TextureActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

public class PayActivity extends Activity {

    private float mPosY;
    private float mCurrentPosY;
    private boolean up_move_action = false;
    private Integer current_second = 60;

    private Timer timer;
    private TimerTask task;

    private TextView tv_pay_second;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);

        Typeface font = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
        // 设置回退Icon
        TextView tv_detail_back = (TextView)findViewById(R.id.tv_detail_back);
        tv_detail_back.setTypeface(font);

        tv_pay_second = findViewById(R.id.tv_pay_second);
        ImageView iv_pay_qr_code = findViewById(R.id.iv_pay_qrCode);
        Bitmap bitmap = ZXingUtils.createQRImage(Data.getCartData_qrcode(),500,500);
        iv_pay_qr_code.setImageBitmap(bitmap);

        initCart();

        // 构建底部图片
        ImageView bottomImage = (ImageView) findViewById(R.id.iv_bottomImage);
        setImage(bottomImage, URLConfig.oss_host + "eshop/slide-1.jpg",false,null,null);
    }

    @Override
    protected void onStart() {
        current_second = 60;
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv_pay_second.setText(current_second.toString());
                    }
                });
                if (current_second.equals(0)){
                    // 跳转到播放广告页面，设置该Activity为第一个页面，清空它上面的栈
                    Intent intent= new Intent(getApplicationContext(), TextureActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
                current_second--;
            }
        };
        timer.schedule(task,2000,1000);
        super.onStart();
    }


    @Override
    protected void onPause() {
        if (timer!=null){
            timer.cancel();
            timer = null;
        }
        if (task != null){
            task.cancel();
            task = null;
        }
        super.onPause();
    }

    /**
     * 返回上一页
     * @param v
     */
    public void  back(View v){
        finish();
    }

    private void initCart(){
        LinearLayout ll_cart = (LinearLayout) findViewById(R.id.ll_cart);
        ll_cart.removeAllViews();
        for (Cart cart: Data.carts){
            View view = View.inflate(getApplicationContext(),R.layout.cart_item,null);
            ImageView image = (ImageView)view.findViewById(R.id.cart_image);
            setImage(image, URLConfig.oss_host + "image/" + cart.getProduct().getSku()+".jpg",true,null,200);
            TextView quantity = (TextView) view.findViewById(R.id.cart_quantity);
            quantity.setText(cart.getQuantity().toString());
            ll_cart.addView(view);
        }
    }
    /**
     * 设置图片
     * @param iv
     * @param path
     */
    private synchronized void setImage(final ImageView iv,  final String path, final Boolean scal_flag, final Integer width, final Integer height) {
        new Thread(){
            @Override
            public void run() {
                File file = new File(getCacheDir(), Base64.encodeToString(path.getBytes(),Base64.DEFAULT));
                if (!file.exists()){
                    try {
                        URL url = new URL(path);
                        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                        conn.setRequestMethod("GET");
                        conn.setConnectTimeout(5000);
                        int code = conn.getResponseCode();
                        if (code == 200){
                            InputStream in = conn.getInputStream();
                            int len = -1;
                            byte[] buffer = new byte[1024];
                            FileOutputStream fos = new FileOutputStream(file);
                            while ((len = in.read(buffer))!=-1) {
                                fos.write(buffer, 0, len);
                            }
                            fos.close();
                            in.close();
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                if (iv!=null){
                    if (scal_flag){
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inJustDecodeBounds = true;
                        BitmapFactory.decodeFile(file.getAbsolutePath(),options);
                        int w = options.outWidth;
                        int h = options.outHeight;
                        // 计算缩放比
                        int scalX = 0;
                        if ( width != null && width != 0){
                            scalX = w/width;
                        }
                        int scalY = h/height;
                        int scal = 1;
                        // 计算宽和高的缩放比，选择缩放比较大的使用
                        if (scalX>scalY && scalX>scal) {
                            scal = scalX;
                        }
                        if (scalY > scalX && scalY > scal) {
                            scal = scalY;
                        }
                        options.inSampleSize = scal;
                        // 取消不读取图片的设置，并且携带缩放比读取图片
                        options.inJustDecodeBounds = false;
                        final Bitmap cacheBitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                iv.setImageBitmap(cacheBitmap);
                            }
                        });
                    }else{
                        final Bitmap cacheBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                iv.setImageBitmap(cacheBitmap);
                            }
                        });
                    }
                }
                super.run();
            }
        }.start();
    }
}
